package com.example.seh.square;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.seh.R;
import com.example.seh.constant.Constant;
import com.example.seh.square.simple.DefaultUseWithServerActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SquareFragment extends Fragment {
    private ListView lvSquare;
    private List<Post> users = new ArrayList<>();
    private SquareAdapter squareAdapter;
    private ImageView ivHead;
    private SmartRefreshLayout refreshLayout;
    private int currentNum = 1;
    private boolean isRefresh = true;
    private Handler myHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    squareAdapter.notifyDataSetChanged();
                    if (!isRefresh) {
                        refreshLayout.finishLoadMore();
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_square, null);

        lvSquare = view.findViewById(R.id.square_listview);
        ivHead = view.findViewById(R.id.iv_head);
        refreshLayout = view.findViewById(R.id.srl);
        refreshLayout.setEnableRefresh(false);

        getData();

        itemClick();

        refreshList();
        return view;
    }

    private void itemClick() {
        lvSquare.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (Constant.isLogin) {
                    Intent intent = new Intent(getActivity(), DefaultUseWithServerActivity.class);
                    Post post = users.get(position);
                    int postId = post.getPostId();
                    Log.e("postId", postId + "");
                    intent.putExtra("postId", postId);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "登录后才能查看详情哦~", Toast.LENGTH_LONG).show();
                }


            }
        });
    }

    private void getData() {
        setData();
        setListener();
        squareAdapter = new SquareAdapter(
                getContext(),
                users,
                R.layout.square_item
        );
        lvSquare.setAdapter(squareAdapter);
    }

    /**
     * 上拉加载更多
     */

    private void setListener() {
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                currentNum++;
                setData();
            }
        });
    }

    /**
     * 点击头部刷新按钮
     */
    private void refreshList() {
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final PopupWindow popupWindow = new PopupWindow();
                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setFocusable(true);
                View view = LayoutInflater.from(getContext()).inflate(R.layout.popup, null);
                popupWindow.setContentView(view);
                popupWindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                        Toast toast = Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT);
                        LinearLayout layout = (LinearLayout) toast.getView();
                        //设置背景
                        //layout.setBackgroundResource(R.color.transparent);
                        //TextView tv = (TextView) layout.getChildAt(0);
                        //设置字体大小
                        //tv.setTextSize(16);
                        //设置字体颜色
                        //tv.setTextColor(Color.BLACK);
                        //显示的位置
                        Display display = getActivity().getWindowManager().getDefaultDisplay();
                        // 获取屏幕高度
                        Point size = new Point();
                        display.getSize(size);
                        toast.setGravity(Gravity.CENTER, 0, size.y / 3);
                        toast.show();

                        popupWindow.dismiss();
                    }
                }, 2000);

                users.clear();
                currentNum = 1;
                isRefresh = true;
                getData();

            }
        });
    }


    private void setData() {


        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(Constant.SQUARE_URL + currentNum)
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String squareData = response.body().string();
                Log.e("数据：", squareData);
                getDataFromJsonData(squareData);
            }


        });


    }

    private void getDataFromJsonData(String studyData) {
        try {
            JSONObject jsonObject = new JSONObject(studyData);
            String PlanDataStr = jsonObject.getString("data");

            if (!PlanDataStr.equals("[]")) {
                Gson gson = new Gson();
                Type type = new TypeToken<List<Post>>() {
                }.getType();
                List<Post> list = gson.fromJson(PlanDataStr, type);
                Log.e("list", list.toString());
                if (isRefresh) {
                    users.addAll(0, list);
                } else {
                    users.addAll(list);

                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "数据加载完了哦~", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Message message = new Message();
        message.what = 1;
        myHandler.sendMessage(message);
    }

}
